package com.devcon5.StudentPlanner;

import baseclasses.Course;
import baseclasses.Grade;
import database.GradeDAO;
import forms.GradeForm;

import android.os.Bundle;
import android.widget.Toast;

public class EditGrade extends GradeForm {

	private Grade grade;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		int id = getIntent().getExtras().getInt( Grade.GRADE_ID ); //Unpack passed intent extras from viewgrades/assignview
		grade = GradeDAO.getGradeById(EditGrade.this, id);	//set grade var to grade object returned by db

		courseTitle.setText(grade.getName());	//populate information about the grade according to db result
		courseSpinner.setSelection(getCoursePosition(grade.getCourseId()));
		scoreEditText.setText(Double.toString(grade.getPointsEarned()));
		outOfEditText.setText(Double.toString(grade.getPointsOutof()));
		percentage.setText(" = " +df.format(grade.getPointsEarned()/grade.getPointsOutof()*100) +"%");

		addButton.setText("Save");
		

	}
	  
	  @Override
	public void addButtonClicked() {	//to save changes to grade
			String title = courseTitle.getText().toString();
			if(title.length()>0){	//if there is a course attached to this grade (might be extra credit)
				int courseId = ((Course)courseSpinner.getSelectedItem()).getId();	//get the course's id
				try{
					//get the information entered for grade and make the variables for grade object match
					double score = Double.parseDouble(scoreEditText.getText().toString());	
					double outOf = Double.parseDouble(outOfEditText.getText().toString());
					grade.setName(title);
					grade.setCourseId(courseId);
					grade.setPointsEarned(score);
					grade.setPointsOutof(outOf);
					GradeDAO.editGrade(EditGrade.this, grade);	//Submit the changes to the db
					
					onBackPressed();
					finish();
				}
				catch(NumberFormatException e){	//invalid entries for score & outOf values
					Toast.makeText(EditGrade.this, "Score and total points must be valid!", Toast.LENGTH_SHORT).show();
				}
			}
			else{	//even if there's no course associated, the grade still needs a name
				Toast.makeText(EditGrade.this, "Grade title cannot be blank!", Toast.LENGTH_SHORT).show();
			}
		super.addButtonClicked();
	}


}
